package com.simpleframe.security;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import com.simpleframe.util.Assert;
import com.simpleframe.util.StringUtil;
import com.simpleframe.util.XmlUtil;

public class ModuleConfigureXmlReader {
	
	private Document document;
	private Extension extension;

	public ModuleConfigureXmlReader(File file){
		try {
//			System.out.println(getClass().getResource(moduleXmlPath));
//			File moduleXmlFile = new File(getClass().getResource(moduleXmlPath).getFile());
			document = XmlUtil.getDocument(file);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		parseExtension(document.getRootElement());
	}
	
	public Extension getExtension(){
		return extension;
	}
	
	private void parseExtension(Element element){
		extension = new Extension();
		String id = element.attributeValue("id");
		String name = element.attributeValue("name");
		
		Assert.notNull(id, "字段名称不能为null");
		Assert.notNull(name, "字段名称不能为null");
		//StringUtil.convertEmpty(label);
		extension.setId(id);
		extension.setName(name);
		
		
		Iterator<Element> it = element.elementIterator("module");
		while (it.hasNext()) {
			Element elem = (Element) it.next();
			parseModules(elem);
		}
	}
	
	private void parseModules(Element element){
		String id = element.attributeValue("id");
		String name = element.attributeValue("name");
		
		Assert.notNull(id, "字段名称不能为null");
		Assert.notNull(name, "字段名称不能为null");
		//StringUtil.convertEmpty(label);
		Module module = new Module();
		module.setId(id);
		module.setName(name);
		extension.addModule(module);
		
		Iterator<Element> it = element.elementIterator("action");
		while (it.hasNext()) {
			Element elem = (Element) it.next();
			parseActions(elem, module);
		}
	}
	
	private void parseActions(Element element, Module module){
		String id = element.attributeValue("id");
		String name = element.attributeValue("name");
		String url = element.attributeValue("url");
		
		Assert.notNull(id, "字段名称不能为null");
		Assert.notNull(name, "字段名称不能为null");
		Assert.notNull(url, "字段名称不能为null");
		
		Action action = new Action();
		action.setId(id);
		action.setName(name);
		action.setUrl(url);
		module.addAction(action);
	}
	
	
	public static void main(String[] args) {
		ModuleConfigureXmlReader xcxr = null;
		try {
//			xcxr = new ModuleConfigureXmlReader("module.xml");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println(xcxr.getExtension().getId());
	}
}
